<!--
 * @Description: 
 * @Date: 2025-09-24 10:32:50
 * @LastEditTime: 2025-10-09 15:08:56
-->
<template>
    <div class="choosePhone flex flex-col">

        <div class="w-100% h-200px relative">
            <van-nav-bar title="靓号选择" left-arrow @click-left="onClickLeft"
                style="background: transparent"></van-nav-bar>
            <img class="w-100% h-100%" src="../assets/img/phone.png" /></img>
        </div>
        <div class="px-10px mt-10px box-border w-100% overflow-hidden flex flex-col gap-10px">
            <div class="w-100% flex overflow-hidden border-rd-10px">
                <span class="bg-#6EDAFE p-10px  color-#000">精准</span>
                <div class="flex-1 overflow-hidden gap-1px flex bg-#0164FC py-8px px-2px">
                    <a-input :ref="el => inputs[number] = el" :key="number" @keyup.delete="handleDelete(number)"
                        @input="handleInput(number)" class="flex-1 overflow-hidden p-0! m-0! text-center border-rd-50%!"
                        v-for="(item, number) in 11" v-model:value="phone[number]" maxlength="1"></a-input>
                    <span @click="restPhone"
                        style="border:1px solid #fff;border-radius: 50%;padding: 0 5px;color: #fff;"><van-icon size="12"
                            name="cross" /></span>
                </div>
                <span class="bg-#0164FC p-10px  color-#fff" @click="handlePhone">搜索</span>
            </div>
            <div class="w-100% flex overflow-hidden border-rd-10px">
                <span class="bg-#6EDAFE p-10px  color-#000">模糊</span>
                <div class="flex-1 overflow-hidden gap-1px flex bg-#0164FC ">
                    <a-input v-model:value="queryData.fuzzyMobile" maxlength="11" :allowClear="true"></a-input>
                </div>
                <span class="bg-#0164FC p-10px  color-#fff" @click="handleDim">搜索</span>
            </div>
            <div class="w-100% flex items-center border-rd-10px overflow-hidden" style="border:1px solid  #d9d9d9">
                <div class="bg-#6EDAFE p-10px  color-#000">
                    号码选段
                </div>
                <div class="flex-1 h-100% text-left px-20px" @click="showPicker = true">
                    <span v-if="!queryData.firstNumber">请选择号码选段</span>
                    <span v-else>{{ queryData.firstNumber }}</span>
                </div>
                <div class="w-40px">
                    <van-icon name="arrow" v-if="!queryData.firstNumber" />
                    <van-icon name="cross" v-else @click.stop="handleGFirst" />
                </div>
            </div>
            <div class="w-100% flex items-center border-rd-10px overflow-hidden" style="border:1px solid  #d9d9d9">
                <div class="bg-#6EDAFE p-10px  color-#000">
                    预存金额
                </div>
                <div class="flex-1 h-100% text-left px-20px" @click="showDepositPicker = true">
                    <span v-if="!queryData.dispot">请选择预存金额</span>
                    <span v-else>{{ queryData.dispot }}</span>
                </div>
                <div class="w-40px">
                    <van-icon name="arrow" v-if="!queryData.dispot" />
                    <van-icon name="cross" v-else @click.stop="handleGDispot" />
                </div>
            </div>
            <div class="w-100% flex gap-10px">
                <span style=" border-radius:20px;"
                    class="bg-#0164FC text-12px px-10px py-3px  flex justify-center items-center color-#fff"
                    v-for="(type, index) in typeList" :key="index" @click="handleSearch(type)">{{ type }}</span>
                <span @click="handleReset" style=" border-radius:20px;"
                    class="bg-#6EDAFE  text-12px px-10px py-3px  flex justify-center items-center color-#000">重置</span>
            </div>
            <div style="display: grid;  grid-template-columns: repeat(5, 1fr);gap: 10px">
                <span style=" border-radius:20px;"
                    class="bg-#EAEAEA font-bold text-12px px-5px py-3px  flex justify-center items-center color-#000"
                    :class="{'activeMenu':activeMenu==index}"
                    v-for="(type, index) in ruleList" :key="index" @click="handleSearch(type,index)">{{ type }}</span>
            </div>
            <div class="px-10px overflow-hidden">
                <a-table :columns="columns" :data-source="phoneList" bordered class="j-table-force-nowrap"
                    :pagination="false" :rowClassName="getRowClassname" :locale="{ emptyText: '暂无数据' }"
                    :rowKey="(record, index) => { return index }">
                </a-table>
                <div class="my-10px w-100% overflow-hidden">
                    <a-pagination layout="prev, pager, next" class="w-100% overflow-hidden" responsive v-model:current="queryData.pageNum" :total="total"
                        :show-quick-jumper="true" @change="handlePageC" />
                </div>
            </div>
        </div>
        <van-tabbar v-model="active" placeholder>
            <van-tabbar-item icon="search" @click="goToPage('/choosePhone')">号码查询</van-tabbar-item>
            <van-tabbar-item icon="orders-o" @click="goToPage('/campOn')">预占列表</van-tabbar-item>
        </van-tabbar>
        <van-dialog v-model:show="ifShow" title="确认预占" show-cancel-button @cancel="handleCancel"
            @confirm="handleConfirm">
            <div class="p-20px text-14px">
                <table border="1" class="w-100%">

                    <tr class="bg-#6EDAFE color-#000 border-none">
                        <th>靓号</th>
                        <th>号码后四位</th>
                        <th>号码类型</th>
                    </tr>
                    <tr>
                        <td>{{ targetRecord.mobile }}</td>
                        <td>{{ targetRecord.lastNumber }}</td>
                        <td>{{ typeList[targetRecord.mobileType - 1] }}</td>
                    </tr>
                </table>
                <P class="mx-0 my-10px text-left color-#000 font-bold text-16px">号码寓意</P>
                <div ref="textareaRef"
                    class="w-100% font-bold text-16px h-200px bg-#EAEAEA overflow-y-auto text-left p-10px">
                    <span> {{ messages }}</span>
                </div>


            </div>

        </van-dialog>
    </div>
    <van-overlay v-model:show="loadingShow" lazy-render z-index="99999">
        <div class="w-100% h-100% flex justify-center items-center">
            <van-loading size="30" vertical color="#1989fa">加载中...</van-loading>
        </div>

    </van-overlay>
    <van-popup v-model:show="showPicker" position="bottom">
        <van-picker :columns="firstColumns" @confirm="onSectionConfirm" @cancel="showPicker = false" />
    </van-popup>
    <van-popup v-model:show="showDepositPicker" position="bottom">
        <van-picker :columns="depositColumns" @confirm="onDepositConfirm" :default-index="0"
            @cancel="showDepositPicker = false" />
    </van-popup>
</template>

<script setup>
import { ref, nextTick, reactive, h, onMounted, onUnmounted, watch } from "vue"
import { useRouter, useRoute } from "vue-router";
import ReconnectingWebSocket from 'reconnecting-websocket';
import { getPhone, getOptionsByGroupCodes, occupy } from "../api/phone"
import { GroupCode } from '@/constant/constant'
import { Toast } from "vant";
const inputs = ref([]);
const router = useRouter();
const active = ref(0);
const phone = ref(Array(11).fill(''))
const lovePhone = ref()
const typeList = ref([])
const ruleList = ref(['AAA', 'AAAA', 'AAAB', 'AABB', 'ABAB', 'ABCD', 'XX88', 'XXX8', 'AAAAB', 'ABCABC', '情侣号', '连7连8', '亲子号', '生日号', '普通靓号', '三口之家', '不带4'])
const ifShow = ref(false);
const targetRecord = ref({})
const messages = ref('')
const socket = ref()
const textareaRef = ref(null)
const loadingShow = ref(false)
const total = ref(0)
const phoneList = ref([])
const showPicker = ref(false)
const showDepositPicker = ref(false)
const firstColumns = ref()
const depositColumns = ref([])
const activeMenu=ref()
const queryData = ref({
    "patternType": "",
    "mobileType": "",
    "dispot": "",
    "mobile": "",
    "pageNum": 1,
    "pageSize": 10,
    "firstNumber": '',
    "fuzzyMobile":''
})

const queryZan = ref({
    mobile: "",
    endTime: "",
    status: "",
    type: "",
    creator: "",

})
const columns = [
    {
        title: '靓号',
        dataIndex: 'mobile',
        width: 120
    },
    {
        title: '后四位',
        dataIndex: 'lastNumber',
        ellipsis: true,
    },
    {
        title: '号码类型',
        dataIndex: 'mobileType',
        ellipsis: true,

        customRender: ({ text }) => {
            return h("div", typeList.value[text - 1]);
        },
    },
    {
        title: "操作",
        dataIndex: 'handle',
        customRender: ({ record }) => {
            return h("div", [
                h(
                    "a",
                    {
                        style: {
                            color: "#1672ea",
                            cursor: "pointer",

                        },
                        onClick: () => handleAffirm(record),
                    },
                    "预占"
                ),

            ]);
        },
    }
];



const editableData = reactive({});

onMounted(async () => {
    await getGroupCodes()
    handleGetList()
    initWebSocket()
})
onUnmounted(() => {
    if (socket.value) {
        socket.value.close()
    }

})

const handleReset = () => {
    queryData.value = {
        "patternType": "",
        "mobileType": "",
        "dispot": "",
        "mobile": "",
        "pageNum": 1,
        "pageSize": 10,
        "firstNumber": ''
    }
    queryData.value.pageNum=1
    loadingShow.value = true
    activeMenu.value=null
    handleGetList()
}
const handlePhone = () => {
    queryData.value.mobile=phone.value.join("")
    queryData.value.pageNum=1
    loadingShow.value = true
    handleGetList()

}
const handleDim = () => {
    console.log(queryData.value.fuzzyMobile)
    queryData.value.pageNum=1
    loadingShow.value = true
    handleGetList()
}
const getGroupCodes = () => {
    return new Promise((resolve, reject) => {
        getOptionsByGroupCodes([GroupCode.PerNumber, GroupCode.MobileType, GroupCode.Dispot]).then(res => {

            if (res.data.code == 200) {
                typeList.value = res.data.data.mobile_type.map(item => item.itemName)
                firstColumns.value = res.data.data.per_number.map(item => item.itemCode)
                depositColumns.value = res.data.data.dispot.map(item => item.itemCode)
                resolve()
            }

        })
    })

}

const handleGDispot = () => {
    queryData.value.dispot = ''
    showPicker.value = false
    queryData.value.pageNum = 1
    loadingShow.value = true
    handleGetList()
}
const handleGFirst = () => {
    queryData.value.firstNumber = ''
    showPicker.value = false
    queryData.value.pageNum = 1
    loadingShow.value = true
    handleGetList()
}
const onSectionConfirm = (value) => {
    queryData.value.firstNumber = value
    showPicker.value = false
    queryData.value.pageNum = 1
    loadingShow.value = true
    handleGetList()
}
const onDepositConfirm = (value) => {
    queryData.value.dispot = value
    showDepositPicker.value = false
    queryData.value.pageNum = 1
    loadingShow.value = true
    handleGetList()
}
const handleConfirm = () => {
    occupy(targetRecord.value.mobile, 1).then(res => {
        if (res.data.code === 200) {
            Toast.success('预占成功')
            targetRecord.value = ""
            router.push("/campOn")
        }
    })
}
const handleSearch = (type,index) => {
   
    if(index!=undefined)activeMenu.value=index
    console.log(activeMenu.value)
    if (typeList.value.includes(type)) {
        queryData.value.mobileType = typeList.value.indexOf(type) + 1
    } else {
        queryData.value.patternType = type
    }
    queryData.value.pageNum = 1
    loadingShow.value = true
    handleGetList()
}
const scrollToBottom = () => {
    nextTick(() => {
        textareaRef.value.scrollTop = textareaRef.value.scrollHeight;
    });
}

const handleGetList = () => {

    getPhone({ ...queryData.value,firstNumbers:[queryData.value.firstNumber],firstColumns:undefined }).then(res => {
        total.value = res.data.data.total
        phoneList.value = res.data.data.records
        phoneList.value.forEach((item, index) => {
            item['sort'] = index
        })
        loadingShow.value = false
    })
}

const handlePageC = () => {
    handleGetList()
}
const edit = (key) => {

    editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
};
const save = (key) => {

    Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
    delete editableData[key];
};


const cancel = (key) => {

    delete editableData[key];
};
const onClickLeft = () => {
    router.push("/dashboard");
}
const handleInput = (index) => {
    nextTick(() => {
        if (phone.value[index] && index < 10) {
            inputs.value[index + 1]?.focus();
        }
    });
};


// 处理删除事件
const handleDelete = (index) => {

    if (!phone.value[index] && index > 0) {
        inputs.value[index - 1]?.focus();
    }
}

const restPhone = () => {
    phone.value = Array(11).fill('')
    queryData.value.mobile = phone.value.join("")
    queryData.value.pageNum = 1
    loadingShow.value = true
    handleGetList()
}
const getRowClassname = (record) => {

    if (record.sort % 2 == 0) {
        return 'bgColor'
    }
}

const handleAffirm = (record) => {
    messages.value = ""
    ifShow.value = true
    targetRecord.value = record
    socket.value.send(record.mobile);
}
const initWebSocket = (pathType) => {
    // 连接后端 WebSocket 服务
    const wsUrl = `ws://sn.wgt.10086.cn/snsst/chudayi/ya/checkup/wsApi/ws/9999/jihao/9999`; // 对应后端 @ServerEndpoint 的 value
    const options = {
        // WebSocket: WebSocket, // 允许你指定一个自定义的 WebSocket 构造函数，通常用于在不同环境中使用不同的 WebSocket 实现
        connectionTimeout: 10000, // 连接初始尝试的超时时间 10000
        maxRetries: 100, // 连接失败后，最大允许的重试次数 100
        maxReconnectionDelay: 10000, // 这是连接重试之间的最大延迟
        minReconnectionDelay: 1000, // 连接重试之间的最小延迟  
        automaticOpen: true,  // 自动连接
        debug: false // enables debug output
    };

    // 方案1：使用原生 WebSocket
    socket.value = new ReconnectingWebSocket(wsUrl, [], options);


    socket.value.onopen = (event) => {
        console.log('WebSocket 连接成功', event);
    };
    socket.value.onmessage = (event) => {
        let response = JSON.parse(event.data)

        if (response.content == "**") {
            response.content = "\n"
        }
        if (response.content == ">>>") {
            response.content = response.content.replace(">>>", "")
        }
        if (response.content == '数据发送结束') {
            return
        }
        messages.value += response.content
        scrollToBottom()
    };

    socket.value.onclose = (event) => {
        console.log('WebSocket 连接关闭', event);
    };
    socket.value.onerror = (error) => {
        console.error('WebSocket 错误', error);
    };
}
const goToPage = (path) => {
    router.push(path)
}
</script>

<style scoped>

.activeMenu{
    background:#0164FC;
    color: #ffffff;
}
:deep(.van-nav-bar) {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;

}

:deep(.van-nav-bar .van-icon),
:deep(.van-nav-bar__title, ) {
    color: #ffffff;
}

:deep(.van-hairline--bottom:after) {

    border: none !important;
}

:deep(.van-tabbar-item--active),
:deep(.van-tabbar--fixed) {
    background: #F5F7FA;
}

/* :deep(.ant-pagination) {
    width: 100%;
    white-space: nowrap;
} */


:deep(.ant-table-thead > tr > th),
:deep(.ant-table-tbody > tr > td) {
    padding: 10px 5px;
    text-align: center;
}

:deep(.van-cell-group) {
    margin: 0;
}

/* :deep(.van-cell) {
    background: #EAEAEA;
} */

::v-deep .bgColor {
    background: #E6F7FF !important;
}


::v-deep .ant-table-thead tr th {
    background: #6EDAFE !important;
}

::v-deep table tbody tr:hover>td {
    background-color: #ffffff !important
}
</style>